/**
 * TODO
 */
package com.bci.pwtz.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.DyxlMapper;
import com.bci.pwtz.mysql.model.Dyxl;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.DyxlService;

/**
 * TODO
 * 
 * @author ICLNetwork Team
 * @version 3.0
 */
@Service
public class DyxlServiceImpl implements DyxlService {
    private DyxlMapper objMapper;

    private BusinessRefService businessRefService;
    private CompanyService companyService;
    public DyxlMapper getObjMapper() {
        return objMapper;
    }

    public void setObjMapper(DyxlMapper objMapper) {
        this.objMapper = objMapper;
    }


    public CompanyService getCompanyService() {
        return companyService;
    }

    public void setCompanyService(CompanyService companyService) {
        this.companyService = companyService;
    }

    private static final Logger _logger = Logger.getLogger(PdbyqServiceImpl.class);

    @Override
    public Dyxl add(Dyxl dyxl) throws PwtzDatabaseException {
        if (_logger.isDebugEnabled()) {
            _logger.debug("add:dyxl=" + dyxl.toString());
        }
        if (dyxl == null) {
            if (_logger.isDebugEnabled()) {
                _logger.debug("add,dyxl is null");
            }
            return null;
        } else {
//            UUID uuid = UUID.randomUUID();
//            dyxl.setDeviceid(uuid.toString());
            dyxl.setStatus(1);
            dyxl.setLastmodifiedtime(new Date());
            dyxl.setCreatedate(new Date());
        }
        try {
            objMapper.insertSelective(dyxl);
        } catch (DataAccessException _e) {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return dyxl;
    }

    @Override
    public int delete(String dyxlId) throws PwtzDatabaseException, CanNotDeleteException {
        int result = 0;
        if (_logger.isDebugEnabled()) {
            _logger.debug("delete:dyxlId=" + dyxlId);
        }
        try {
            boolean bl = businessRefService.canDelete("T_DYXL", dyxlId);
            if (!bl) {
                throw new CanNotDeleteException();
            }
            result = objMapper.deleteById(dyxlId,new Date());
        } catch (DataAccessException _e) {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public int update(Dyxl dyxl) throws PwtzDatabaseException {
        int result = 0;
        if (_logger.isDebugEnabled()) {
            _logger.debug("update:dyxl=" + dyxl.toString());
        }
        if (dyxl == null) {
            if (_logger.isDebugEnabled()) {
                _logger.debug("update,dyxl is null");
            }
            return 0;
        }else{
            dyxl.setLastmodifiedtime(new Date());
        }
        try {
            result = objMapper.updateByPrimaryKeySelective(dyxl);
        } catch (DataAccessException _e) {
            _logger.error(ExceptionUtils.getStackTrace(_e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public Dyxl load(String dyxlId) throws PwtzDatabaseException {
        if (_logger.isInfoEnabled()) {
            _logger.info("load:dyxlId=" + dyxlId);
        }
        Dyxl dyxl = null;
        try {
            dyxl = objMapper.selectByPrimaryKey(dyxlId);
        } catch (DataAccessException e) {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (dyxl != null) {
            _logger.debug("load:result dyxl=" + dyxl.toString());
        }
        return dyxl;
    }

    @Override
    public PaginationList<Dyxl> findDyxl(String devicename,Long companyid, int portalType,String[] medLineCodes,int deviceType,String transformerCode, String beginTime, String endTime, int pageSize, int pageNo)
            throws PwtzDatabaseException {
        PaginationList<Dyxl> paginationList = new PaginationList<Dyxl>();

        if (_logger.isInfoEnabled()) {
            _logger.info("findDybx:|devicename=" + devicename+"|beginTime=" + beginTime+"|endTime=" + endTime+"|companyid="+companyid+"|portalType="+portalType+"|medLineCodes="+PwtzUtils.parseCharacterArrayToString(medLineCodes)+"|deviceType="+deviceType+"|transformerCode="+transformerCode+"|pageSize="+pageSize+"|pageNo="+pageNo);
        }
        List<Dyxl> list = null;
        int beginIndex = pageSize * pageNo - pageSize;
        String companyidStr="";
        String[] companyids=null;
        if(portalType==PwtzConstants.PORTAL_TYPE_WEB){
            companyidStr=companyService.findChildrensId(companyid,null);
            if(companyidStr!=null && companyidStr.length()>0){
                companyidStr=companyidStr.substring(0,companyidStr.length()-1);
                        companyids =companyidStr.split(",");
            }
        }
        try {
            list = objMapper.selectDeviceList(devicename,companyid, companyids, portalType,medLineCodes, deviceType,transformerCode,beginTime, endTime, beginIndex, pageSize);
        } catch (DataAccessException e) {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list != null) {
            _logger.debug("findDyxl:result menu=" + list.toString());
        }
        int totalCount = 0;
        int totalPage = 1;
        if (pageSize != 0) {
            try {
                totalCount = objMapper.selectDeviceCount(devicename,companyid, companyids, portalType, medLineCodes, deviceType,transformerCode,beginTime, endTime);
            } catch (DataAccessException e) {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        } else {
            pageNo = 1;
            if (list != null && list.size() > 0) {
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    public BusinessRefService getBusinessRefService()
    {
        return businessRefService;
    }

    public void setBusinessRefService(BusinessRefService businessRefService)
    {
        this.businessRefService = businessRefService;
    }
    
    @Override
    public PaginationList<Dyxl> selectDyxlByPdbyq(int deviceType,String transformerCode,String deviceName,Long companyId,int pageSize, int pageNo)throws PwtzDatabaseException {
        PaginationList<Dyxl> paginationList = new PaginationList<Dyxl>();

        List<Dyxl> list = null;
        int beginIndex = pageSize * pageNo - pageSize;
        try {
            list = objMapper.selectByPdbyq(deviceType, transformerCode, deviceName, companyId, beginIndex, pageSize);
        } catch (DataAccessException e) {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list != null) {
            _logger.debug("selectDyxlByPdbyq:result menu=" + list.toString());
        }
        int totalCount = 0;
        int totalPage = 1;
        if (pageSize != 0) {
            try {
                totalCount = objMapper.selectDeviceCountByPdbyq(deviceType, transformerCode, deviceName, companyId);
            } catch (DataAccessException e) {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        } else {
            pageNo = 1;
            if (list != null && list.size() > 0) {
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public List<Dyxl> selectDyxlAllBypdbyq(int deviceType, String transformerCode, String deviceName, Long companyId) throws PwtzDatabaseException {
        List<Dyxl> list = null;
        try {
            list = objMapper.selectByAllPdbyq(deviceType, transformerCode, deviceName, companyId);
        } catch (DataAccessException e) {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return list;
    }

}
